<?php

namespace App\Model;

//模板消息 订阅/退订
class MpTplUnsubModel
{
    private static string $table = 'brz_mp_tpl_unsub';

    private function exists(string $openid)
    {
        $mysqlFac = new MysqliFactory();
        $client = $mysqlFac->createMysqlClient();
        $client->queryBuilder()->where('openid', $openid)->get(self::$table);
        try {
            $ret = $client->execBuilder();
            return boolval($ret);
        } catch (\Throwable $e) {
            echo $e->getMessage(), "\n";
            return $e->getMessage();
        }
    }

    //订阅
    public function subscribe(string $openid)
    {
        $this->exec($openid, false);
    }

    //退订
    public function unsubscribe(string $openid)
    {
        $this->exec($openid, true);
    }

    function exec(string $openid, bool $isUnsubscribe)
    {
        $mysqlFac = new MysqliFactory();
        $client = $mysqlFac->createMysqlClient();
        $isUnsub = $isUnsubscribe ? 1 : 0;
        if ($this->exists($openid)) {
            //0.记录存在时更新状态
            $edit = ['is_unsub' => $isUnsub,];
            $client->queryBuilder()
                ->where('openid', $openid)
                ->update(self::$table, $edit);
        } else {
            //1.订阅时不生成新纪录
            if (!$isUnsubscribe) {
                return;
            }
            //2.退订时添加新纪录
            $data = ['is_unsub' => $isUnsub, 'openid' => $openid,];
            $client->queryBuilder()->insert(self::$table, $data);
        }
        try {
            $client->execBuilder();
        } catch (\Throwable $e) {
            echo $e->getMessage(), "\n";
        }
    }
}
